import axios from 'axios'
import type { User } from '@/stores/user'
import type { Elderly, HealthRecord, MedicationRecord } from '@/stores/elderly'

// 创建axios实例
export const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080',
  timeout: 10000
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 认证相关API
export const authAPI = {
  login: (username: string, password: string) =>
    api.post<{ user: User; token: string }>('/auth/login', { username, password }),
  
  register: (userData: {
    username: string
    password: string
    name: string
    role: 'admin' | 'user'
    phone?: string
    email?: string
  }) => api.post<{ user: User; token: string }>('/auth/register', userData),
  
  logout: () => api.post('/auth/logout')
}

// 老人管理API
export const elderlyAPI = {
  getAll: () => api.get<Elderly[]>('/elderly'),
  
  getById: (id: string) => api.get<Elderly>(`/elderly/${id}`),
  
  create: (elderly: Omit<Elderly, 'id' | 'createdAt' | 'updatedAt'>) =>
    api.post<Elderly>('/elderly', elderly),
  
  update: (id: string, updates: Partial<Elderly>) =>
    api.put<Elderly>(`/elderly/${id}`, updates),
  
  delete: (id: string) => api.delete(`/elderly/${id}`),
  
  // 获取用户绑定的老人
  getByUserId: (userId: string) => api.get<Elderly[]>(`/elderly/user/${userId}`)
}

// 健康记录API
export const healthRecordAPI = {
  getByElderlyId: (elderlyId: string) =>
    api.get<HealthRecord[]>(`/health-records/${elderlyId}`),
  
  create: (record: Omit<HealthRecord, 'id'>) =>
    api.post<HealthRecord>('/health-records', record),
  
  update: (id: string, updates: Partial<HealthRecord>) =>
    api.put<HealthRecord>(`/health-records/${id}`, updates),
  
  delete: (id: string) => api.delete(`/health-records/${id}`)
}

// 用药记录API
export const medicationRecordAPI = {
  getByElderlyId: (elderlyId: string) =>
    api.get<MedicationRecord[]>(`/medication-records/${elderlyId}`),
  
  create: (record: Omit<MedicationRecord, 'id'>) =>
    api.post<MedicationRecord>('/medication-records', record),
  
  update: (id: string, updates: Partial<MedicationRecord>) =>
    api.put<MedicationRecord>(`/medication-records/${id}`, updates),
  
  delete: (id: string) => api.delete(`/medication-records/${id}`)
}

// 健康报告API
export const reportAPI = {
  generateHealthReport: (elderlyId: string, startDate: string, endDate: string) =>
    api.post(`/reports/health/${elderlyId}`, { startDate, endDate }),
  
  downloadReport: (reportId: string) =>
    api.get(`/reports/download/${reportId}`, { responseType: 'blob' })
}

export default api 